package com.example.menuvirtualclient.repository;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.util.Log;

import com.example.menuvirtualclient.core.*;
import com.example.menuvirtualclient.data.Repository;
import com.example.menuvirtualclient.util.Common;

public class DishMenuRepository extends Repository<DishMenu>{

	private static final String LOGTAG = "DishMenuRepository";	
	
	public DishMenuRepository(Context context) {
		super(context);
	}
	
	public boolean exist(DishMenu entity) {
		SQLiteDatabase db = null;
		try{
			List<DishMenu> list = new ArrayList<DishMenu>();
			String[] filter = new String[2];
			filter[0] = Integer.toString(entity.getDishId());
			filter[1] = Integer.toString(entity.getMenuId());
			if(!_session.IsOpen())
				_session.Open();
			
			db = _session.Connection();
			Cursor cursor = db.rawQuery("SELECT menuid, dishid FROM Dishes_Menues WHERE dishid = ? AND menuid = ? ", filter);
			
			cursor.moveToFirst();
		    while (!cursor.isAfterLast()) {
		    	list.add(BuildNewEntity(cursor));
		    	cursor.moveToNext();
		    }
		    cursor.close();
		    db.close();
		    if(list != null && list.size() > 0)
		    	return true;
		    else
		    	return false;
		}
		catch(SQLiteException ex){
			Log.e(LOGTAG, ex.getMessage());
			throw ex;
		}		
		finally{
			if(db != null)
				if(db.isOpen()) db.close();
		}
	}
	
	@Override
	public void Insert(DishMenu entity) {
		SQLiteDatabase db = null;
		try{
			ContentValues newRow = new ContentValues();
			newRow.put("menuid", entity.getMenuId());			
			newRow.put("dishid", entity.getDishId());
			
			if(!_session.IsOpen())
				_session.Open();
			
			db = _session.Connection();
			db.insert(getTableName(), null, newRow);
			
			db.close();
		}
		catch(NullPointerException ex){
			Log.e(LOGTAG, ex.getMessage());
		}
		catch(SQLiteException ex){
			Log.e(LOGTAG, ex.getMessage());
		}
		catch(Exception ex){
			Log.e(LOGTAG, ex.getMessage());		
		}
		finally{
			if(db != null)
				if(db.isOpen()) db.close();
			_session.Close();
		}
	}
		
	@Override
	public String getTableName() {
		return "Dishes_Menues";
	}
	
	@Override
	public DishMenu BuildNewEntity(Cursor cursor) {
		DishMenu entity = new DishMenu();
		entity.setMenuId(cursor.getInt(0));
		entity.setDishId(cursor.getInt(1));

		return entity;
	}
}
